// Copyright (c) 2025 Bytedance Ltd. and/or its affiliates
// SPDX-License-Identifier: MIT

import { EditorView } from "@codemirror/view";
import { langs } from "@uiw/codemirror-extensions-langs";
import { vscodeDark, vscodeLight } from "@uiw/codemirror-theme-vscode";
import CodeMirror from "@uiw/react-codemirror";
import { Code, ExternalLink, Monitor } from "lucide-react";
import { useTheme } from "next-themes";
import { useEffect, useRef, useState } from "react";

import { LoadingAnimation } from "~/components/deer-flow/loading-animation";
import { ScrollContainer } from "~/components/deer-flow/scroll-container";
import { Button } from "~/components/ui/button";
import { useMessage, useStore } from "~/core/store";
import { env } from "~/env";
import { cn } from "~/lib/utils";

export function ResearchReportBlock({
  className,
  messageId,
}: {
  className?: string;
  researchId: string;
  messageId: string;
}) {
  const store = useStore();
  const message = useMessage(messageId);
  const contentRef = useRef<HTMLDivElement>(null);
  const previewUrl = `${env.NEXT_PUBLIC_FILE_SERVER_URL}/resumes/${store.threadId}.html`;
  const [viewMode, setViewMode] = useState<"preview" | "code">("code");
  // Get current theme
  const { resolvedTheme } = useTheme();
  const [mounted, setMounted] = useState(false);

  // Set mounted state to true after component mounts
  useEffect(() => {
    setMounted(true);
  }, []);

  // Add line wrapping extension
  const extensions = [langs.html(), EditorView.lineWrapping];

  // Select the theme based on the current theme
  const theme = mounted && resolvedTheme === "dark" ? vscodeDark : vscodeLight;

  return (
    <div
      ref={contentRef}
      className={cn("flex h-full w-full flex-col pb-2", className)}
    >
      <div className="flex items-center gap-2">
        <Button
          variant="ghost"
          size="sm"
          className={cn(
            "bg-background/80 hover:bg-background/90 flex items-center gap-2 backdrop-blur-sm",
            viewMode === "code" && "bg-background/90",
          )}
          disabled={message?.isStreaming}
          onClick={() => setViewMode("code")}
        >
          <Code className="h-4 w-4" />
          代码
        </Button>
        <Button
          variant="ghost"
          size="sm"
          className={cn(
            "bg-background/80 hover:bg-background/90 flex items-center gap-2 backdrop-blur-sm",
            viewMode === "preview" && "bg-background/90",
          )}
          disabled={message?.isStreaming}
          onClick={() => setViewMode("preview")}
        >
          <Monitor className="h-4 w-4" />
          预览
        </Button>
        <Button
          variant="ghost"
          size="sm"
          className="bg-background/80 hover:bg-background/90 flex items-center gap-2 backdrop-blur-sm"
          disabled={message?.isStreaming}
          onClick={() => window.open(previewUrl, "_blank")}
        >
          <ExternalLink className="h-4 w-4" />
          打开
        </Button>
      </div>
      {message?.content && (
        <div className="flex-1 overflow-hidden">
          {viewMode === "preview" ? (
            <iframe
              src={previewUrl}
              title="HTML Preview"
              className="mt-2 h-full w-full border-0!"
              sandbox="allow-same-origin allow-scripts"
            />
          ) : (
            <ScrollContainer
              className="h-full w-full pt-2"
              scrollShadowColor="var(--card)"
              autoScrollToBottom={message?.isStreaming}
            >
              <CodeMirror
                value={message.content}
                theme={theme}
                extensions={extensions}
                basicSetup={{
                  lineNumbers: false,
                  highlightActiveLine: false,
                  highlightActiveLineGutter: false,
                  foldGutter: false,
                }}
                editable={false}
                className="min-h-full w-full text-sm"
                style={{ maxWidth: "100%" }}
                height="auto"
              />
            </ScrollContainer>
          )}
        </div>
      )}
      {message?.isStreaming && <LoadingAnimation className="my-6" />}
    </div>
  );
}
